/*
 *  Copyright 2011 Bryce Alcock.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package com.ecocrypt.collections;

/**
 *
 * @author Bryce L. Alcock
 */
public class ByteBuffer {

    public static final  int BUFFER_SIZE=1024;
    private byte[] buffer = new byte[BUFFER_SIZE];
    private int contentLength;

    public void reset(){
        // Just resetting the content length.
        contentLength=0;
    }

    public boolean add(byte b)
    {
        if(contentLength<buffer.length)
        {
            buffer[contentLength++]=b;
            return true;
        }
        return false;
    }

    public boolean isFull()
    {
        return contentLength>=buffer.length;
    }

    public int capacity()
    {
        return buffer.length - contentLength;
    }

    public int add(byte[] ba)
    {
        int bytesCopied = Math.max(capacity(),ba.length);
        System.arraycopy(ba, 0, buffer, contentLength, bytesCopied);
        return bytesCopied;
    }

    public byte[] getBufferContents()
    {
        byte[] newBuffer = new byte[contentLength];
        System.arraycopy(buffer, 0, newBuffer, 0, contentLength);
        return newBuffer;
    }

    public byte[] getBuffer(){
        return buffer;
    }
}
